#include "bga/graphics/Texture2D.h"

#include <SFML/Graphics/Image.hpp>

using namespace std;

namespace bga
{

Texture2D::Texture2D() : TextureObject()
{
    this->target = GL_TEXTURE_2D;
    this->textureWidth = 0;
    this->textureHeight = 0;
}

Texture2D::~Texture2D()
{
}

void Texture2D::setTextureWidth(unsigned int width)
{
    this->textureWidth = width;
}

unsigned int Texture2D::getTextureWidth() const
{
    return this->textureWidth;
}

void Texture2D::setTextureHeight(unsigned int height)
{
    this->textureHeight = height;
}

unsigned int Texture2D::getTextureHeight() const
{
    return this->textureHeight;
}

void Texture2D::allocateTexture()
{
    glTexImage2D(this->target, 0, this->internalFormat, this->textureWidth, this->textureHeight, 0, this->dataFormat, this->dataType, 0);
    /// generate mipmap
    glGenerateMipmapEXT(target);
    this->allocated = true;
}

void Texture2D::loadImage()
{
    sf::Image image;
    if(!imageFilenameList.empty() && !imageFilenameList[0].empty() && !imageLoaded)
    {
        image.LoadFromFile(imageFilenameList[0]);

        if ( !this->allocated || this->textureWidth != image.GetWidth() || this->textureHeight != image.GetHeight() )
        {
            this->textureWidth = image.GetWidth();
            this->textureHeight =  image.GetHeight();
            allocateTexture();
        }

        /// load image data
        glTexSubImage2D(this->target, 0, 0, 0, this->textureWidth, this->textureHeight, this->dataFormat, this->dataType, image.GetPixelsPtr());
        /// generate mipmap
        glGenerateMipmapEXT(this->target);

        this->imageLoaded = true;
    }
}

}
